package blog.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import blog.entity.Options;
import blog.service.OptionsService;
import blog.utils.ImageUtil;

@Controller
@RequestMapping("/options")
public class OptionsController {
	@Resource
	OptionsService optionsService;

	/**
	 * 后台页面列表
	 */
	@RequestMapping(value = "")
	public String index(ModelMap m) {
		Options options = optionsService.getOptions();
		m.put("options", options);
		return "Options/options";

	}

	/**
	 * 更新基本信息,注意要有两张图片要处理
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String updateOption(MultipartFile sitePhoto, MultipartFile webChatPhoto, Options options)
			throws IOException {
		options.setOptionAboutsitePhoto(ImageUtil.resizeImage(sitePhoto.getBytes(), 150, "jpg"));
		options.setOptionAboutsiteWechatphoto(ImageUtil.resizeImage(webChatPhoto.getBytes(), 430, "jpg"));
		optionsService.updateOptions(options);

		return "forward:/options";
	}

	/**
	 * 提取出的图片数据,传到前台展示
	 */
	@RequestMapping("/photo/{photoType}")
	public void showPhoto(@PathVariable("photoType") String photoType, HttpServletResponse response)
			throws IOException {

		Options options = optionsService.getOptions();
		response.setContentType("image/jpg");
		ServletOutputStream outstream = response.getOutputStream();
		if (options != null) {

			if ("sitephoto".equals(photoType)) {
				if (options.getOptionAboutsitePhoto() != null) {
					outstream.write(options.getOptionAboutsitePhoto());
				}

			} else {
				if (options.getOptionAboutsiteWechatphoto() != null) {
					outstream.write(options.getOptionAboutsiteWechatphoto());
				}

			}
		}
		outstream.flush();
	}

}
